package com.sc.nft.controller;


import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.sc.nft.annotation.UserLogin;
import com.sc.nft.controller.request.IdPageRequest;
import com.sc.nft.controller.request.IdRequest;
import com.sc.nft.controller.request.SignInRequest;
import com.sc.nft.controller.request.SupplementarySignatureRequest;
import com.sc.nft.dao.ActivityTaskUserPriceDao;
import com.sc.nft.entity.ActivityBasics;
import com.sc.nft.entity.ActivityTaskPlan;
import com.sc.nft.entity.ActivityTaskUserPrize;
import com.sc.nft.entity.vo.*;
import com.sc.nft.enums.RedisKeyEnum;
import com.sc.nft.pool.UserPool;
import com.sc.nft.service.ActivityBasicsService;
import com.sc.nft.service.ActivityTaskPlanService;
import com.sc.nft.sup.ErrorCode;
import com.sc.nft.sup.PageRequest;
import com.sc.nft.sup.PageResult;
import com.sc.nft.sup.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * (ActivityBasics)表控制层
 *
 * @author 王伟成
 * @since 2023-09-14 17:09:21
 */

@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/activityBasics")
@Api(tags = "活动列表")
public class ActivityBasicsController {
    /**
     * 服务对象
     */
    private final ActivityBasicsService activityBasicsService;
    private final ActivityTaskPlanService taskPlanService;
    private final ActivityTaskUserPriceDao activityTaskUserPriceDao;
    private final Redisson redisson;



    @ApiOperation(value = "获取活动", notes = "获取活动", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/page", produces = MediaType.APPLICATION_JSON_VALUE)
    @UserLogin
    public PageResult<WebActivityBasicsVO> page(@RequestBody PageRequest pageRequest) {

        Page<ActivityBasics> page = activityBasicsService.page(pageRequest.toMp());
        Page<WebActivityBasicsVO> pageResult = PageResult.copyListPage(page, WebActivityBasicsVO.class);
        for (WebActivityBasicsVO record : pageResult.getRecords()) {
            record.setStartTimeStamp(record.getStartTime().getTime());
            record.setEndTimeStamp(record.getEndTime().getTime());
            record.setNowTimeStamp( DateTime.now().getTime());
        }
        return PageResult.success(pageResult);
    }

    @ApiOperation(value = "获取活动详情内容.包含奖券数量,竞猜号码数量 开奖号码", notes = "获取活动详情内容.包含奖券数量,竞猜号码数量 开奖号码", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/detailsById", produces = MediaType.APPLICATION_JSON_VALUE)
    @UserLogin
    public Result<WebActivityBasicsDetailsVO> webDetailsById(@RequestBody IdRequest idRequest) {
        return Result.success(activityBasicsService.webDetailsById(idRequest.getId(), UserPool.getUser()), WebActivityBasicsDetailsVO.class);
    }

    @ApiOperation(value = "获取活动详情内容 签到详情内容", notes = "获取活动详情内容 签到详情内容", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/signInDetailsById", produces = MediaType.APPLICATION_JSON_VALUE)
    @UserLogin
    public Result<SignInActivityBasicsDetailsVO> signInDetailsById(@RequestBody IdRequest idRequest) {
        return Result.success(activityBasicsService.signInDetailsById(idRequest.getId(), UserPool.getUser()));
    }


    @ApiOperation(value = "任务记录", notes = "任务记录", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/taskRecord", produces = MediaType.APPLICATION_JSON_VALUE)
    @UserLogin
    public PageResult<ActivityTaskRecordVO> taskRecord(@RequestBody IdPageRequest request) {
        Page<ActivityTaskPlan> activityTaskPlanPage = taskPlanService.taskRecord(request.toMp(), UserPool.getUser(), request.getId());
        Page<ActivityTaskRecordVO> page = new Page<>(activityTaskPlanPage.getCurrent(),activityTaskPlanPage.getSize(),activityTaskPlanPage.getTotal());

        List<ActivityTaskRecordVO> result = Lists.newArrayList();
        for (ActivityTaskPlan record : activityTaskPlanPage.getRecords()) {
            ActivityTaskRecordVO activityTaskRecordVO = new ActivityTaskRecordVO();
            activityTaskRecordVO.setTaskName(record.getTaskName());
            activityTaskRecordVO.setTaskFinishName(record.getTaskFinishTime());
            List<ActivityTaskUserPrize> taskPlans = activityTaskUserPriceDao.getByTaskPlanId(record.getId());
            List<ActivityTaskPrizeVO> prizeVOS = Lists.newArrayList();
            for (ActivityTaskUserPrize taskPrize : taskPlans) {
                ActivityTaskPrizeVO vo = new ActivityTaskPrizeVO();
                vo.setPrizeCount(taskPrize.getPrizeCount());
                vo.setPrizeName(taskPrize.getPrizeName());
                prizeVOS.add(vo);
            }
            activityTaskRecordVO.setTaskPrizes(prizeVOS);
            result.add(activityTaskRecordVO);
        }
        page.setRecords(result);


        return PageResult.success(page);
    }


    @ApiOperation(value = "活动记录", notes = "活动记录", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/activityRecord", produces = MediaType.APPLICATION_JSON_VALUE)
    @UserLogin
    public PageResult<ActivityRecordVO> activityRecord(@RequestBody PageRequest pageRequest) {
        return PageResult.success(activityBasicsService.activityRecord(pageRequest.toMp()));
    }


    @ApiOperation(value = "用户签到", notes = "用户签到", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/userSignIn", produces = MediaType.APPLICATION_JSON_VALUE)
    @UserLogin
    public Result userSignIn(@RequestBody IdRequest idRequest) {
        RLock lock = redisson.getLock(RedisKeyEnum.USER_SIGN_IN.getKey() + UserPool.getUser().getId());
        try{
            boolean res = lock.tryLock(3, 10, TimeUnit.SECONDS);
            if (res) {
                activityBasicsService.userSignIn(idRequest.getId(),UserPool.getUser());
            }else {
                return Result.fail(ErrorCode.LATER_TRY);
            }
        } catch (InterruptedException e) {
            return Result.fail("当前人数过多，请稍后再试");
        } finally {
            lock.unlock();
        }
        return Result.success();
    }

//5.8.0上线注释接口，如果以后需要签到历史天数，可以使用。
//    @ApiOperation(value = "指定天数签到", notes = "指定天数签到", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
//    @PostMapping(value = "/specifyactivitySignIn", produces = MediaType.APPLICATION_JSON_VALUE)
//    @UserLogin
//    public Result specifyactivitySignIn(@Valid @RequestBody SignInRequest request)  {
//        RLock lock = redisson.getLock(RedisKeyEnum.USER_SIGN_IN.getKey() + UserPool.getUser().getId());
//        try{
//            boolean res = lock.tryLock(3, 10, TimeUnit.SECONDS);
//            if (res) {
//                activityBasicsService.userSignIn(request.getSignInActivityId(),request.getSignInDate(),request.getSignInDay(), UserPool.getUser());
//            }else {
//                return Result.fail(ErrorCode.LATER_TRY);
//            }
//        } catch (InterruptedException e) {
//            return Result.fail("当前人数过多，请稍后再试");
//        } finally {
//            lock.unlock();
//        }
//        return Result.success();
//    }


    @ApiOperation(value = "用户补签", notes = "用户补签", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/userSupplementarySignIn", produces = MediaType.APPLICATION_JSON_VALUE)
    @UserLogin
    public Result userSupplementarySignIn(@RequestBody SupplementarySignatureRequest idRequest) {
        RLock lock = redisson.getLock(RedisKeyEnum.USER_SUPPLEMENTARY_SIGNATURE.getKey() + UserPool.getUser().getId());
        try{
            boolean res = lock.tryLock(3, 10, TimeUnit.SECONDS);
            if (res) {
                activityBasicsService.userSupplementarySignIn(idRequest.getId(),idRequest.getSupplementarySignatureCardDayNum(),UserPool.getUser());
            }else {
                return Result.fail(ErrorCode.LATER_TRY);
            }
        } catch (InterruptedException e) {
            return Result.fail("当前人数过多，请稍后再试");
        } finally {
            lock.unlock();
        }
        return Result.success();
    }

//    @ApiOperation(value = "testDate", notes = "testDate", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
//    @PostMapping(value = "/testDate", produces = MediaType.APPLICATION_JSON_VALUE)
//    public Result testDate() {
//        activityBasicsService.testDate();
//        return Result.success();
//    }


}
